<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="800px">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="设备ID" prop="deviceId">
            <el-input v-model="formData.deviceId" placeholder="请输入设备ID" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="formData.deviceName" placeholder="请输入设备名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备型号" prop="model">
            <el-input v-model="formData.model" placeholder="请输入设备型号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="安装位置" prop="location">
            <el-input
              v-model="formData.location"
              placeholder="请输入安装位置，如：主楼/5层/501室/东南角"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="能耗类型" prop="energyType">
            <el-select v-model="formData.energyType" class="!w-full" placeholder="请选择能耗类型">
              <el-option
                v-for="item in energyTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备状态" prop="status">
            <el-select v-model="formData.status" class="!w-full" placeholder="请选择设备状态">
              <el-option
                v-for="item in deviceStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标准电压(V)" prop="voltage">
            <el-input-number
              v-model="formData.voltage"
              :precision="2"
              :min="0"
              :max="1000"
              class="!w-full"
              placeholder="请输入标准电压"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标准电流(A)" prop="currents">
            <el-input-number
              v-model="formData.currents"
              :precision="2"
              :min="0"
              :max="1000"
              class="!w-full"
              placeholder="请输入标准电流"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标准功率(kW)" prop="activePower">
            <el-input-number
              v-model="formData.activePower"
              :precision="2"
              :min="0"
              :max="1000"
              class="!w-full"
              placeholder="请输入标准功率"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="累计能耗(kWh)" prop="energyConsumption">
            <el-input-number
              v-model="formData.energyConsumption"
              :precision="2"
              :min="0"
              class="!w-full"
              placeholder="请输入累计能耗"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备温度(℃)" prop="temperature">
            <el-input-number
              v-model="formData.temperature"
              :precision="2"
              :min="-40"
              :max="150"
              class="!w-full"
              placeholder="请输入设备温度"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import * as DeviceApi from '@/api/energy/device'
import { DeviceVO, deviceStatusOptions, energyTypeOptions } from '@/api/energy/device'
import { useValidator } from '@/hooks/web/useValidator'
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import Dialog from '@/components/Dialog/src/Dialog.vue'
import { cloneDeep } from 'lodash-es'

const { required } = useValidator()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formRef = ref()

const defaultFormData: DeviceVO = {
  id: 0,
  deviceId: '',
  deviceName: '',
  model: '',
  location: '',
  energyType: '',
  voltage: undefined as unknown as number,
  currents: undefined as unknown as number,
  activePower: undefined as unknown as number,
  energyConsumption: undefined as unknown as number,
  temperature: undefined as unknown as number,
  status: 'normal',
  createTime: undefined as unknown as Date
}

const formData = ref<DeviceVO>({ ...defaultFormData })

const formRules = reactive({
  deviceId: [required],
  deviceName: [required],
  model: [required],
  location: [required],
  energyType: [required]
})

const emit = defineEmits(['success'])

const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? '新增能耗设备' : '编辑能耗设备'
  formData.value = { ...defaultFormData }

  // 编辑
  if (id) {
    formLoading.value = true
    try {
      const res = await DeviceApi.getDevice(id)
      formData.value = res
    } finally {
      formLoading.value = false
    }
  }
}

const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return

  // 提交请求
  formLoading.value = true
  try {
    // 克隆一份表单数据
    const reqData = cloneDeep(formData.value)
    if (reqData.id) {
      await DeviceApi.updateDevice(reqData)
      ElMessage.success('修改成功')
    } else {
      await DeviceApi.createDevice(reqData)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

// 向外暴露方法
defineExpose({ open })
</script>
